package org.squabble.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.squabble.service.AccountService;
import org.squabble.web.account.EmailChangeCommand;


@Component(value="emailChangeValidator")
public class EmailChangeValidator extends PasswordRequiredValidator implements Validator {

	@Autowired
	AccountService accountService;

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return EmailChangeCommand.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		super.validate(arg0, errors);
		EmailChangeCommand ecc = (EmailChangeCommand) arg0;
		if (accountService.emailExists(ecc.getNewEmail())) {
			errors.rejectValue("newEmail", "EmailChangeCommand.newEmail[in.use]");
		}
	}

}
